import { createStore, OpenFile, ViewerState } from "../../core";

import Download, { DownloadProps } from "./Download";
import DownloadButton from "./DownloadButton";
import DownloadMenuItem, { DownloadMenuItemProps } from "./DownloadMenuItem";
import getFileName from "./getFileName";

import { useMemo } from "react";
import { DownloadPlugin, DownloadPluginProps, StoreProps } from "./interface";

const downloadPlugin = (props?: DownloadPluginProps): DownloadPlugin => {
  const store = useMemo(() => createStore<StoreProps>({}), []);

  const defaultFileNameGenerator = (file: OpenFile) =>
    typeof file.data === "object" ? "document.pdf" : getFileName(file.name);

  const DownloadDecorator = (downloadProps: DownloadProps) => (
    <Download
      {...downloadProps}
      fileNameGenerator={
        props
          ? props.fileNameGenerator || defaultFileNameGenerator
          : defaultFileNameGenerator
      }
      store={store}
    />
  );

  const DownloadButtonDecorator = () => (
    <DownloadDecorator>
      {(props) => <DownloadButton {...props} />}
    </DownloadDecorator>
  );

  const DownloadMenuItemDecorator = (props: DownloadMenuItemProps) => (
    <DownloadDecorator>
      {(p) => (
        <DownloadMenuItem
          onClick={() => {
            p.onClick();
            props.onClick();
          }}
        />
      )}
    </DownloadDecorator>
  );

  return {
    onViewerStateChange: (viewerState: ViewerState): ViewerState => {
      store.update("file", viewerState.file);
      return viewerState;
    },
    Download: DownloadDecorator,
    DownloadButton: DownloadButtonDecorator,
    DownloadMenuItem: DownloadMenuItemDecorator,
  };
};

export default downloadPlugin;
